/// Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Windows.Forms;
using NUnit.Framework;
using NUnit.Extensions.Forms;
using Microsoft.VSPowerToys.PackInstaller;
using Microsoft.VSPowerToys.PackInstallerDataModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Diagnostics;
using System.Reflection;

namespace GUITestScenarios
{
    [TestFixture]
    public class MainGUITests : NUnitFormTest
    {
        #region Private Data and Methods
        private PackInstallerForm packInstallForm;
        private bool secondTrip;
        private int tripCount;
        private ErrorMessages errorMessages;

        /// <summary>
        /// In order to test forms with ShowDialog under NUnitForms, you have to
        /// provide a "handler" method for the Form. Normally, this handler would
        /// contain the test logic. But, that doesn't work well for the PackInstaller
        /// because it uses threads. 
        /// 
        /// So, the test logic will be in a delegate method attched to the PackInstaller 
        /// form. Therefore, this is a skeleton handler and used for most tests.
        /// </summary>
        private void GenericFormHandler()
        {
        }

        /// <summary>
        /// Form handler to install the Managed Stack Explorer tool
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InstallManagedStackExplorerHandler(object sender, EventArgs e)
        {
            if (tripCount == 0)
            {
                tripCount++;
                // Make sure we are in install mode
                RadioButtonTester radioTester = new RadioButtonTester("headerPanel.installationRadio", "PackInstallerForm");
                radioTester.Click();

                // Check the box to install the Managed Stack Explorer
                CheckBoxTester ManagedStackExplorertoolCheckBoxTester = new CheckBoxTester("Tools and Utilities.toolsPanel.Managed Stack Explorer.layoutPanel.installToolCheckBox", "PackInstallerForm");
                ManagedStackExplorertoolCheckBoxTester.Click();

                // Set up the handler's for the forms
                ExpectModal("ProgressResultsForm", "GenericFormHandler");
                ExpectModal("LicenseAgreementDownloadForm", "GenericFormHandler");
                ExpectModal("MultipleLicenseAgreementForm", "LicenseFormHandler");

                ButtonTester installSoftwareButtonTester = new ButtonTester("installSoftwareButton", "PackInstallerForm");
                // Verify that the Install button is enabled
                if (installSoftwareButtonTester.Properties.Enabled != true)
                {
                    errorMessages.Add("Install software button is disabled after one tool was selected.");
                }

                // Install the MSE tool
                installSoftwareButtonTester.Click();
            }
            else
            {
                packInstallForm.Close();
            }
        }

        /// <summary>
        /// Private method to install the Managed Stack Explorer tool
        /// </summary>
        private void InstallManagedStackExplorer()
        {
            packInstallForm = new PackInstallerForm(TestStrings.GeneralTestPackFeedXml);
            packInstallForm.OnPacksLoaded += new EventHandler<EventArgs>(InstallManagedStackExplorerHandler);
            installedToolCount = 1;
            packInstallForm.OnToolsInstalled += new EventHandler<EventArgs>(InstallProgressFormHandler);
            ExpectModal("PackInstallerForm", "GenericFormHandler");
            packInstallForm.ShowDialog();
        }

        /// <summary>
        /// Form handler to remove the Managed Stack Explorer tool
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RemoveManagedStackExplorerHandler(object sender, EventArgs e)
        {
            ButtonTester buttonTester = new ButtonTester("refreshListButton", "PackInstallerForm");
            if (tripCount == 2)
            {
                tripCount++;
                // Make sure we are in install mode
                RadioButtonTester radioTester = new RadioButtonTester("headerPanel.installationRadio", "PackInstallerForm");
                radioTester.Click();

                // Verify that MSE has been installed
                bool explorerInstalled = false;
                ToolSummaryControlTester managedStackExplorerSummaryTester = new ToolSummaryControlTester("Tools and Utilities.toolsPanel.Managed Stack Explorer", "PackInstallerForm");
                ControlFinder managedStackExplorerInstalledBox = new ControlFinder("Tools and Utilities.toolsPanel.Managed Stack Explorer.layoutPanel.glyphLayout.installedBox", packInstallForm);

                // If the Managed Stack Explorer was installed, the Pack Installer makes the 
                // installedBox control visible on the MSE layout panel. So, if we search for the
                // control and do not find it, the Find method throws a NoSuchControlException which 
                // indicates that installation failed or there is a bug in the Pack Installer.
                try
                {
                    managedStackExplorerInstalledBox.Find();
                    explorerInstalled = true;
                }
                catch (NoSuchControlException)
                {
                    errorMessages.Add("Managed Stack Explorer is not marked as installed on the PackInstallerForm.");
                }

                if (explorerInstalled == true)
                {
                    // Click the maintenanceRadio button
                    radioTester = new RadioButtonTester("headerPanel.maintenanceRadio", "PackInstallerForm");
                    radioTester.Click();
                    // Check the MSE tool box
                    CheckBoxTester managedStackExplorertoolCheckBoxTester = new CheckBoxTester("Tools and Utilities.toolsPanel.Managed Stack Explorer.layoutPanel.installToolCheckBox", "PackInstallerForm");
                    managedStackExplorertoolCheckBoxTester.Click();

                    // If a test's logic did not redisplay all the tools,
                    // this may throw a ControlNotVisibleException when the method tries 
                    // to click MSE's checkbox
                    try
                    {
                        // Remove the MSE tool
                        ButtonTester installSoftwareButtonTester = new ButtonTester("installSoftwareButton", "PackInstallerForm");
                        installSoftwareButtonTester.Click();
                    }
                    catch (ControlNotVisibleException)
                    {
                        errorMessages.Add("RemoveManagedStackExplorerHandler: Test logic did not redisplay all tools.");
                        // Click the Refresh List button so the test will exit
                        buttonTester.Click();
                    }
                }
            }
            else
            {
                // After it refreshes, click the Exit button.
                buttonTester = new ButtonTester("exitButton", "PackInstallerForm");
                buttonTester.Click();
            }
        }

        /// <summary>
        /// Method to remove the Managed Stack Explorer tool
        /// </summary>
        private void RemoveManagedStackExplorer()
        {
            packInstallForm = new PackInstallerForm(TestStrings.GeneralTestPackFeedXml);
            packInstallForm.OnPacksLoaded += new EventHandler<EventArgs>(RemoveManagedStackExplorerHandler);
            packInstallForm.OnToolsInstalled += new EventHandler<EventArgs>(RemovalProgressFormHandler);
            ExpectModal("PackInstallerForm", "GenericFormHandler");
            packInstallForm.ShowDialog();     
        }

        private void RemoveInstalledPacks()
        {
            packInstallForm = new PackInstallerForm(TestStrings.GeneralTestPackFeedXml);
            packInstallForm.OnPacksLoaded += new EventHandler<EventArgs>(RemoveInstalledPacksHandler);
            packInstallForm.OnToolsInstalled += new EventHandler<EventArgs>(RemovalProgressFormHandler);
            ExpectModal("PackInstallerForm", "GenericFormHandler");
            packInstallForm.ShowDialog();
        }

        private void RemoveInstalledPacksHandler(object sender, EventArgs e)
        {
            ButtonTester buttonTester = new ButtonTester("refreshListButton", "PackInstallerForm");
            ButtonTester installSoftwareButtonTester = new ButtonTester("installSoftwareButton", "PackInstallerForm");
            PanelControlTester packListControlTester = new PanelControlTester("packListPanel", "PackInstallerForm");

            if (tripCount == 2)
            {
                tripCount++;

                // Click the maintenanceRadio button
                RadioButtonTester radioTester = new RadioButtonTester("headerPanel.maintenanceRadio", "PackInstallerForm");
                radioTester.Click();

                foreach (Control pack in packListControlTester.InnerControls)
                {
                    CheckBoxTester installPackCheckBoxTester = new CheckBoxTester(pack.Name + ".headerPanel.installPackCheckBox");

                    // Check each Pack for installation
                    if (installPackCheckBoxTester.Properties.Visible)
                    {
                        installPackCheckBoxTester.Click();
                    }
                }

                installSoftwareButtonTester.Click();
            }
            else
            {
                // After it refreshes, click the Exit button.
                buttonTester = new ButtonTester("exitButton", "PackInstallerForm");
                buttonTester.Click();
            }
        }


        private void LicenseFormHandler()
        {
            ButtonTester buttonTester = new ButtonTester("acceptButton", "MultipleLicenseAgreementForm");
            buttonTester.Click();
        }

        private int installedToolCount;
        /// <summary>
        /// Logic to verify installation of the Managed Stack Explorer tool
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InstallProgressFormHandler(object sender, EventArgs e)
        {
            RichTextBoxTester textBoxTester = new RichTextBoxTester("progressResultsTextBox", "ProgressResultsForm");
            ButtonTester buttonTester = new ButtonTester("cancelCloseButton", "ProgressResultsForm");
            string successMessage = installedToolCount + " / " + installedToolCount + " tools installed successfully.";

            // Verify that the promoPictureBox control is shown
            PictureBoxTester pictureBoxTester = new PictureBoxTester("promoPictureBox", "ProgressResultsForm");
            try
            {
                // Since NUnitForms doesn't actually find the control until you use it, we
                // check an arbitrary property to verify that the control is there
                // If NUnitForms can't find the control, it throws NoSuchControlException
                // Which we catch and handle
                if (pictureBoxTester.Properties.BackColor != System.Drawing.Color.FromArgb(((int)(((byte)(228)))), ((int)(((byte)(235)))), ((int)(((byte)(248))))))
                {
                    errorMessages.Add("BackColor on promoPictureBox is wrong.");
                }
            }
            catch (NoSuchControlException)
            {
                errorMessages.Add("promoPictureBox was not found.");
            }

            ControlTester ct = new ControlTester("queueCompleteLabel", "ProgressResultsForm");
            if (ct.Text != successMessage)
            {
                errorMessages.Add("Tool installation seems to have failed." + "\n\tqueueCompleteLabel text == '" + ct.Text + "'");
            }
            // Close the progress form
            buttonTester.Click();
        }
        /// <summary>
        /// Logic to verify removal of the Managed Stack Explorer tool
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RemovalProgressFormHandler(object sender, EventArgs e)
        {
            RichTextBoxTester textBoxTester = new RichTextBoxTester("progressResultsTextBox", "ProgressResultsForm");
            ButtonTester buttonTester = new ButtonTester("cancelCloseButton", "ProgressResultsForm");
            string successMessage = installedToolCount + " / " + installedToolCount + " tools removed successfully.";


            ControlTester ct = new ControlTester("queueCompleteLabel", "ProgressResultsForm");
            if (ct.Text != successMessage)
            {
                errorMessages.Add("Tool removal seems to have failed.");
            }
            // Close the progress form
            buttonTester.Click();
        }
        #endregion

        /// <summary>
        /// Verify that Visual Studio is not running before we run the test suite
        /// </summary>
        [TestFixtureSetUp]
        public void Init()
        {
            Process[] visualStudioProcesses = Process.GetProcessesByName("devenv");
            TextWriter errorWriter = Console.Error;
            if (visualStudioProcesses.Length != 0)
            {
                errorWriter.WriteLine("You must close Visual Studio before running the test suite.");
                Assert.IsTrue(false);
            }

        }

        private string downloadedFeedFileName;

        #region Refresh List button test
        /// <summary>
        /// Click the Refresh List button. This test will:
        /// a. Install a modified tool list XML file locally (e.g. removed some tools that are
        ///    in the current Pack List.)
        /// b. Disconnect from the network and verify that the local tool list is displayed
        /// c. Reconnect to the network 
        /// d. Click the refresh button and verify that the "real" list is displayed.
        /// 
        /// </summary>
        [Test]
        public void RefreshListButtonTest()
        {
            errorMessages = new ErrorMessages();
            TextWriter errorWriter = Console.Error;

            // Replace any previously downloaded feed file with one that does not contain
            // MSBee
            downloadedFeedFileName = Path.Combine(Application.CommonAppDataPath, "ToolFeedAtom.xml");
            File.Copy(TestStrings.GeneralTestPackFeedXml, downloadedFeedFileName, true);
            File.SetAttributes(downloadedFeedFileName, (File.GetAttributes(downloadedFeedFileName) & (~FileAttributes.ReadOnly)));

            // Have the user disable the network so that our modified file is used
            ExpectModal("Disable Network", "GenericFormHandler");
            DialogResult dialogResult = MessageBox.Show("Please disable or disconnect your network and then click OK.", "Disable Network", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (dialogResult != DialogResult.OK)
            {
                errorWriter.WriteLine("User clicked Cancel in response to Disable Network message.");
                Console.WriteLine("User clicked Cancel in response to Disable Network message.");
                Assert.AreEqual(DialogResult.OK, dialogResult);
            }

            System.Threading.Thread.Sleep(2000);

            ExpectModal("PackInstallerForm", "GenericFormHandler");

            // Instantiate Pack Installer and display the main form
            packInstallForm = new PackInstallerForm(String.Empty);
            ExpectModal("Enable Network", "GenericFormHandler");
            packInstallForm.OnPacksLoaded += new EventHandler<EventArgs>(RefreshListHandler);
            secondTrip = false;
            packInstallForm.ShowDialog();
            errorMessages.printErrors("RefreshListButtonTest");
            Assert.AreEqual(0, errorMessages.Count, "RefreshListButtonTest failed. Check Console output for error messages.");

        }

        /// <summary>
        /// Callback delegate for Refresh List button logic
        /// </summary>
        public void RefreshListHandler(object sender, EventArgs e)
        {
            ButtonTester installSoftwareButtonTester = new ButtonTester("installSoftwareButton", "PackInstallerForm");
            string expectedMessage;
            if (secondTrip == false)
            {
                // Verify that the feed file was not downloaded!
                expectedMessage = "The list of tools could not be downloaded.  The last known good list will be used instead.";
                StatusStripTester ct = new StatusStripTester("statusStrip1", "PackInstallerForm");
                if (ct.Properties.Items[0].Text != expectedMessage)
                {
                    errorMessages.Add("Expected message '" + expectedMessage + "'\nbut found '" + ct.Properties.Items[0].Text + "'");
                }

                // Verify that MSBee is not contained in the displayed feed file.
                try
                {
                    CheckBoxTester toolCheckBoxTester = new CheckBoxTester("MSBee.layoutPanel.installToolCheckBox", "PackInstallerForm");
                    // This should throw an exception if the control was not added to the pack list
                    // If the control was added, it should not be visible
                    if (toolCheckBoxTester.Properties.Visible != false)
                    {
                        errorMessages.Add("Tool 'MSBee' was unexpectedly displayed.");
                    }
                }
                catch (NoSuchControlException)
                {
                    // Do nothing; The test passes
                }

                MessageBox.Show("Please reconnect your network and then click OK.", "Enable Network", MessageBoxButtons.OK, MessageBoxIcon.Information);
                secondTrip = true;
                File.Delete(downloadedFeedFileName);
                System.Threading.Thread.Sleep(3000);
                // Click the Refresh List button
                ButtonTester buttonTester = new ButtonTester("refreshListButton", "PackInstallerForm");
                buttonTester.Click();
            }
            else
            {
                // After it refreshes, check the status message and click the Exit button.
                expectedMessage = "The tool feed downloaded successfully.";
                StatusStripTester ct = new StatusStripTester("statusStrip1", "PackInstallerForm");
                if (ct.Properties.Items[0].Text != expectedMessage)
                {
                    errorMessages.Add("Expected message '" + expectedMessage + "'\nbut found '" + ct.Properties.Items[0].Text + "'");
                }
                // Verify that MSBee is contained in the displayed feed file.
                try
                {
                    CheckBoxTester toolCheckBoxTester = new CheckBoxTester("MSBee.layoutPanel.installToolCheckBox", "PackInstallerForm");
                    // This should throw an exception is the control was not added to the pack list
                    // If the control was added, it should be visible
                    if (toolCheckBoxTester.Properties.Visible != true)
                    {
                        errorMessages.Add("Tool 'MSBee' was NOT displayed.");
                    }
                }
                catch (NoSuchControlException)
                {
                    errorMessages.Add("Tool 'MSBee' was NOT displayed.");
                }
                ButtonTester exitButtonTester = new ButtonTester("exitButton", "PackInstallerForm");
                exitButtonTester.Click();
            }
        }
        #endregion

        #region Click on link to Power Toys Home page
        /// <summary>
        /// Click the Power Toys home page link and 
        /// wait for it to display in the registerd browser. Hint - it's a good idea
        /// to run this particular test several time with different registered browsers.
        /// 
        /// This test covers the test plan's Main GUI Functions sccenario #3
        /// </summary>
        [Test]
        public void ClickPowerToysHomePageExerciser()
        {
            errorMessages = new ErrorMessages();
            packInstallForm = new PackInstallerForm(TestStrings.GeneralTestPackFeedXml);
            packInstallForm.OnPacksLoaded += new EventHandler<EventArgs>(ClickPowerToysHomePageHandler);
            ExpectModal("PackInstallerForm", "GenericFormHandler");
            packInstallForm.ShowDialog();
            errorMessages.printErrors("ClickPowerToysHomePageExerciser");
            Assert.AreEqual(0, errorMessages.Count, "ClickPowerToysHomePageExerciser failed. Check Console output for error messages.");
        }
        public void ClickPowerToysHomePageHandler(object sender, EventArgs e)
        {
            LinkLabelTester homePageTester = new LinkLabelTester("packInstallerHomePageLink", "PackInstallerForm");
            homePageTester.Click();
            packInstallForm.Close();
            return;
        }
        #endregion

        #region Test tool sorting 

        /// <summary>
        /// Basic sort test to verify that all sort buttons
        /// sort by the intended field and use ascending order
        /// when clicked the first time; Also verifies that clicking a sort control 
        /// multiple times toggles the sort order between ascending and descending
        /// </summary>
        [Test]
        public void ToolSortingTest()
        {
            tripCount = 0;
            errorMessages = new ErrorMessages();

            // Install the MSE tool
            InstallManagedStackExplorer();

            packInstallForm = new PackInstallerForm(TestStrings.GeneralTestPackFeedXml);
            packInstallForm.OnPacksLoaded += new EventHandler<EventArgs>(ToolSortHandler);
            installedToolCount = 1;
            packInstallForm.OnToolsInstalled += new EventHandler<EventArgs>(InstallProgressFormHandler);
            ExpectModal("PackInstallerForm", "GenericFormHandler");
            packInstallForm.ShowDialog();

            // Remove the Managed Stack Explorer 
            RemoveManagedStackExplorer();

            errorMessages.printErrors("ToolSortingTest");
            Assert.AreEqual(0, errorMessages.Count, "ToolSortingTest failed. Check Console output for error messages.");
    }

        /// <summary>
        /// Test logic for basic sort tests
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ToolSortHandler(object sender, EventArgs e)
        {
            ButtonTester buttonTester ;
            SortItemControlTester sortMethodTester;
            string[] sortMethodNames = { "Default Groups", "Tool Name", "Author", "Release Date", "Currently Installed", };
            string[] expectedPacksDefaultGroups = { "Code Samples and Snippets", "Starter Kits", "Tools and Utilities", "Visual Studio 2005 Extensions", };
            string[] expectedPacksToolName = { "0 - 9", "I - P", "Q - Z", };
            string[] expectedPacksAuthor = { "I - P", };
            string[] expectedPacksCurrentlyInstalled = { "Installed Tools", "Not Installed Tools", };
            string[] expectedPacksReleaseDate = 
                {
                    "Released in the last 30 days",
                    "Released in the last 90 days",
                    "Released in the last 180 days",
                    "Released in the last 360 days",
                    "A long time ago",
                };
            object[] args = { sender, e };

            if (tripCount == 1)
            {
                #region Pack Installer is initially sorted by Default Groups in ascending order
                // Verify that Pack Installer is initially sorted by 
                // Default Groups in ascending order.
                VerifySortMethodAndOrder(ToolItem.SortByField.DefaultGroup, SortOrder.Ascending);

                // The Managed Stack Explorer should be first in the Tools and Utilities pack 
                FindManagedStackExplorer("Tools and Utilities", 1);
                VerifyExpectedPacks(expectedPacksDefaultGroups);
                #endregion

                #region Sort by Tool Name
                sortMethodTester = new SortItemControlTester("Tool Name" + "SortControl");

                // NunitForms click method did not work correctly for this control so 
                // we invoke the click method directly.
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);

                VerifySortMethodAndOrder(ToolItem.SortByField.ToolName, SortOrder.Ascending);
                VerifyExpectedPacks(expectedPacksToolName);
                // The Managed Stack Explorer should be first in the I - P pack 
                FindManagedStackExplorer("I - P" , 1);
                #endregion

                #region Sort by Author
                sortMethodTester = new SortItemControlTester("Author" + "SortControl");
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);

                VerifySortMethodAndOrder(ToolItem.SortByField.Author, SortOrder.Ascending);
                VerifyExpectedPacks(expectedPacksAuthor);
                // The Managed Stack Explorer should be third in the I - P pack 
                FindManagedStackExplorer("I - P" , 3);
                #endregion

                #region Sort by Release Date
                sortMethodTester = new SortItemControlTester("Release Date" + "SortControl");
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);

                VerifySortMethodAndOrder(ToolItem.SortByField.ReleaseDate, SortOrder.Ascending);
                VerifyAllPacks(expectedPacksReleaseDate);
                // The Managed Stack Explorer should be first in the A long time ago pack 
                FindManagedStackExplorer("A long time ago" ,1);
                #endregion

                #region Sort by Default Groups
                sortMethodTester = new SortItemControlTester("Default Groups" + "SortControl");
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                VerifySortMethodAndOrder(ToolItem.SortByField.DefaultGroup, SortOrder.Ascending);
                VerifyExpectedPacks(expectedPacksDefaultGroups);

                // The Managed Stack Explorer should be first in the Tools and Utilities pack 
                FindManagedStackExplorer("Tools and Utilities", 1);
                #endregion

                #region Sort by whether or not Installed
                sortMethodTester = new SortItemControlTester("Currently Installed" + "SortControl");
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);

                VerifySortMethodAndOrder(ToolItem.SortByField.CurrentlyInstalled, SortOrder.Ascending);
                VerifyExpectedPacks(expectedPacksCurrentlyInstalled);
                // The Managed Stack Explorer should be first in the Installed Tools pack 
                FindManagedStackExplorer("Installed Tools",1);
                #endregion

                #region Clicking a sort control multiple times toggles the sort order
                // Verify that clicking a sort control multiple times toggles 
                // the sort order between ascending and descending

                // High level test that just clicks each control several times
                // and verifies that the sort control properties for sor tmethod and
                // sort order toggle as expected
                for (ToolItem.SortByField sortType = ToolItem.SortByField.DefaultGroup;
                    sortType < ToolItem.SortByField.MicrosoftProvidedTool;
                    sortType++)
                {
                    int index = (int)sortType - 1;
                    sortMethodTester = new SortItemControlTester(sortMethodNames[index] + "SortControl");
                    sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                    VerifySortMethodAndOrder(sortType, SortOrder.Ascending);
                    sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                    VerifySortMethodAndOrder(sortType, SortOrder.Descending);
                    sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                    VerifySortMethodAndOrder(sortType, SortOrder.Ascending);
                    sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                    VerifySortMethodAndOrder(sortType, SortOrder.Descending);
                }

                // More detailed tests of selected sort methods
                PackListControlTester packListTester ;

                // Sort by Release Date - 
                // The number of tools in the A long time ago pack will change 
                // as the tool releases age over time but the Managed Stack Explorer 
                // should always be be first in ascending order and last in descending order

                // The first click should get ascending order
                sortMethodTester = new SortItemControlTester("Release Date" + "SortControl");
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                VerifySortMethodAndOrder(ToolItem.SortByField.ReleaseDate, SortOrder.Ascending);
                // The Managed Stack Explorer should be first in the A long time ago pack 
                FindManagedStackExplorer("A long time ago", 1);

                // Click a second time to get descending
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                VerifySortMethodAndOrder(ToolItem.SortByField.ReleaseDate, SortOrder.Descending);
                packListTester = new PackListControlTester("A long time ago", "PackInstallerForm");
                // The Managed Stack Explorer should be last in the A long time ago pack 
                FindManagedStackExplorer("A long time ago", packListTester.Properties.CurrentPackData.Tools.Count);

                // Third click should get ascending again
                sortMethodTester = new SortItemControlTester("Release Date" + "SortControl");
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                VerifySortMethodAndOrder(ToolItem.SortByField.ReleaseDate, SortOrder.Ascending);
                FindManagedStackExplorer("A long time ago", 1);

                // Fouth time should get descending again
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                VerifySortMethodAndOrder(ToolItem.SortByField.ReleaseDate, SortOrder.Descending);
                packListTester = new PackListControlTester("A long time ago", "PackInstallerForm");
                // The Managed Stack Explorer should be last in the A long time ago pack 
                FindManagedStackExplorer("A long time ago", packListTester.Properties.CurrentPackData.Tools.Count);

                // Sort by Tool Name
                sortMethodTester = new SortItemControlTester("Tool Name" + "SortControl");
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                VerifySortMethodAndOrder(ToolItem.SortByField.ToolName, SortOrder.Ascending);
                // The Managed Stack Explorer should be first in the I - P pack 
                FindManagedStackExplorer("I - P", 1);

                // Click a second time to get descending
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                VerifySortMethodAndOrder(ToolItem.SortByField.ToolName, SortOrder.Descending);
                packListTester = new PackListControlTester("I - P", "PackInstallerForm");
                // The Managed Stack Explorer should be last in the I - P pack 
                FindManagedStackExplorer("I - P", packListTester.Properties.CurrentPackData.Tools.Count);

                // Third click should get ascending again
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                VerifySortMethodAndOrder(ToolItem.SortByField.ToolName, SortOrder.Ascending);
                FindManagedStackExplorer("I - P", 1);

                // Fouth time should get descending again
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                VerifySortMethodAndOrder(ToolItem.SortByField.ToolName, SortOrder.Descending);
                packListTester = new PackListControlTester("I - P", "PackInstallerForm");
                FindManagedStackExplorer("I - P", packListTester.Properties.CurrentPackData.Tools.Count);

                // Sort by Author - first click should be ascending
                sortMethodTester = new SortItemControlTester("Author" + "SortControl");
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                VerifySortMethodAndOrder(ToolItem.SortByField.Author, SortOrder.Ascending);
                // The Managed Stack Explorer should be third in the I - P pack 
                FindManagedStackExplorer("I - P", 3);

                // Click a second time to get descending
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                VerifySortMethodAndOrder(ToolItem.SortByField.Author, SortOrder.Descending);
                // The Managed Stack Explorer should be 11th in the I - P pack 
                FindManagedStackExplorer("I - P", 11);

                // Third click should get ascending again
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                VerifySortMethodAndOrder(ToolItem.SortByField.Author, SortOrder.Ascending);
                FindManagedStackExplorer("I - P", 3);

                // Fouth time should get descending again
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                VerifySortMethodAndOrder(ToolItem.SortByField.Author, SortOrder.Descending);
                // The Managed Stack Explorer should be 11th in the I - P pack 
                FindManagedStackExplorer("I - P", 11);
                #endregion

                tripCount++;
                // Click the Exit button.
                buttonTester = new ButtonTester("exitButton", "PackInstallerForm");
                buttonTester.Click();
            }
            else
            {
                errorMessages.Add("ToolSortHandler: Unexpected Multiple Trips");
                // Click the Exit button.
                buttonTester = new ButtonTester("exitButton", "PackInstallerForm");
                buttonTester.Click();
            }
        }

        /// <summary>
        /// Sort tools by release date (dsecending) and verify that they are 
        /// still sorted by release date after declining a license agreement
        /// during an installation.
        /// </summary>
        [Test]
        public void ToolSortAndDeclineLicenseTest()
        {
            tripCount = 0;
            errorMessages = new ErrorMessages();
            packInstallForm = new PackInstallerForm(TestStrings.GeneralTestPackFeedXml);
            packInstallForm.OnPacksLoaded += new EventHandler<EventArgs>(ToolSortAndRefreshHandler);
            ExpectModal("PackInstallerForm", "GenericFormHandler");
            packInstallForm.ShowDialog();
            errorMessages.printErrors("ToolSortAndDeclineLicenseTest");
            Assert.AreEqual(0, errorMessages.Count, "ToolSortAndDeclineLicenseTest failed. Check Console output for error messages.");
        }

        /// <summary>
        /// Test logic for ToolSortAndDeclineLicenseTest
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ToolSortAndRefreshHandler(object sender, EventArgs e)
        {
            SortItemControlTester sortMethodTester;
            PackListControlTester packListTester;
            object[] args = { sender, e };

            // Sort by Release Date in ascending order 
            sortMethodTester = new SortItemControlTester("Release Date" + "SortControl");
            sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
            VerifySortMethodAndOrder(ToolItem.SortByField.ReleaseDate, SortOrder.Ascending);

            // Click a second time to get descending
            sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
            VerifySortMethodAndOrder(ToolItem.SortByField.ReleaseDate, SortOrder.Descending);
            packListTester = new PackListControlTester("A long time ago", "PackInstallerForm");
            // The Managed Stack Explorer should be last in the A long time ago pack 
            FindManagedStackExplorer("A long time ago", packListTester.Properties.CurrentPackData.Tools.Count);

            //  Now do logic similar to the decline license tests
            ButtonTester installSoftwareButtonTester = new ButtonTester("installSoftwareButton", "PackInstallerForm");

            // Check the box to install the Managed Stack Explorer
            CheckBoxTester ManagedStackExplorertoolCheckBoxTester = new CheckBoxTester("A long time ago.toolsPanel.Managed Stack Explorer.layoutPanel.installToolCheckBox", "PackInstallerForm");
            ManagedStackExplorertoolCheckBoxTester.Click();

            // Verify that the Install button is now enabled
            if (installSoftwareButtonTester.Properties.Enabled != true)
            {
                errorMessages.Add("Install software button is disabled after one tool was selected.");
            }

            // Need an ExpectModal to handle the license download and agreement forms.
            // If we decline the license we do NOT expect a progress form to be displayed
            // so we intentionally do not put an ExpectModal for it. Then, if one is displayed 
            // the test will fail due to the unexpected dialog form showing up.
            ExpectModal("LicenseAgreementDownloadForm", "GenericFormHandler");
            ExpectModal("MultipleLicenseAgreementForm", "DeclineLicenseFormHandler");
            installSoftwareButtonTester.Click();

            // Should return here after the license is declined.
            // Sorting should still be by Release Date (Descending)

            VerifySortMethodAndOrder(ToolItem.SortByField.ReleaseDate, SortOrder.Descending);
            packListTester = new PackListControlTester("A long time ago", "PackInstallerForm");
            // The Managed Stack Explorer should be last in the A long time ago pack 
            FindManagedStackExplorer("A long time ago", packListTester.Properties.CurrentPackData.Tools.Count);

            // Click the Exit button.
            ButtonTester buttonTester = new ButtonTester("exitButton", "PackInstallerForm");
            buttonTester.Click();
        }

        /// <summary>
        /// This test sorts tools by release date and verify that they are 
        /// still sorted by release date after installing a tool
        /// </summary>
        [Test]
        public void ToolSortAndInstallToolTest()
        {
            tripCount = 0;
            installedToolCount = 1;

            errorMessages = new ErrorMessages();
            packInstallForm = new PackInstallerForm(TestStrings.GeneralTestPackFeedXml);
            packInstallForm.OnPacksLoaded += new EventHandler<EventArgs>(ToolSortAndInstallHandler);
            packInstallForm.OnToolsInstalled += new EventHandler<EventArgs>(InstallProgressFormHandler);
            ExpectModal("PackInstallerForm", "GenericFormHandler");
            packInstallForm.ShowDialog();
            RemoveManagedStackExplorer();
            errorMessages.printErrors("ToolSortAndInstallToolTest");
            Assert.AreEqual(0, errorMessages.Count, "ToolSortAndInstallToolTest failed. Check Console output for error messages.");
        }

        /// <summary>
        /// Test logic for ToolSortAndInstallToolTest
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ToolSortAndInstallHandler(object sender, EventArgs e)
        {
            SortItemControlTester sortMethodTester;
            PackListControlTester packListTester;
            object[] args = { sender, e };

            if (tripCount == 0)
            {
                // On the first trip through this handler, we want to select sorting
                // by release date (descending) and install the MSE tool
                tripCount++;

                // Sort by Release Date in ascending order 
                sortMethodTester = new SortItemControlTester("Release Date" + "SortControl");
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                VerifySortMethodAndOrder(ToolItem.SortByField.ReleaseDate, SortOrder.Ascending);

                // Click a second time to get descending
                sortMethodTester.Invoke("sortMethodNameLabel_Click", args);
                VerifySortMethodAndOrder(ToolItem.SortByField.ReleaseDate, SortOrder.Descending);
                packListTester = new PackListControlTester("A long time ago", "PackInstallerForm");
                // The Managed Stack Explorer should be last in the A long time ago pack 
                FindManagedStackExplorer("A long time ago", packListTester.Properties.CurrentPackData.Tools.Count);

                #region Install Managed Stack Explorer

                // Check the box to install the Managed Stack Explorer
                CheckBoxTester ManagedStackExplorertoolCheckBoxTester = new CheckBoxTester("A long time ago.toolsPanel.Managed Stack Explorer.layoutPanel.installToolCheckBox", "PackInstallerForm");
                ManagedStackExplorertoolCheckBoxTester.Click();

                // Set up the handler's for the forms
                ExpectModal("ProgressResultsForm", "GenericFormHandler");
                ExpectModal("LicenseAgreementDownloadForm", "GenericFormHandler");
                ExpectModal("MultipleLicenseAgreementForm", "LicenseFormHandler");

                ButtonTester installSoftwareButtonTester = new ButtonTester("installSoftwareButton", "PackInstallerForm");
                // Verify that the Install button is enabled
                if (installSoftwareButtonTester.Properties.Enabled != true)
                {
                    errorMessages.Add("Install software button is disabled after one tool was selected.");
                }

                // Install the MSE tool
                installSoftwareButtonTester.Click();
                #endregion

            }
            else if (tripCount == 1)
            {
                // On the second trip through this handler, we verify that sorting 
                // is by Release Date (Descending) and exit.
                // The main test drive will remove MSE
                tripCount++;

                // If the sorting is still by Release Date (Descending)
                // The Managed Stack Explorer should be last in the A long time ago pack 
                packListTester = new PackListControlTester("A long time ago", "PackInstallerForm");
                FindManagedStackExplorer("A long time ago", packListTester.Properties.CurrentPackData.Tools.Count);

                // Click the Exit button.
                ButtonTester buttonTester = new ButtonTester("exitButton", "PackInstallerForm");
                buttonTester.Click();
            }
        }

        private void VerifySortMethodAndOrder(ToolItem.SortByField expectedMethod, SortOrder expectedOrder)
        {
            SortListControlTester sortListControlTester = new SortListControlTester("sortListControl");
            if (sortListControlTester.Properties.CurrentlySelectedSortMethod != expectedMethod)
            {
                errorMessages.Add("ToolSortHandler: CurrentlySelectedSortMethod != " + expectedMethod + "; It is " + sortListControlTester.Properties.CurrentlySelectedSortMethod.ToString());
            }
            if (sortListControlTester.Properties.CurrentSortOrder != expectedOrder)
            {
                errorMessages.Add("ToolSortHandler: CurrentSortOrder != " + expectedOrder + "; It is " + sortListControlTester.Properties.CurrentSortOrder.ToString());
            }

        }

        private void VerifyExpectedPacks(string[] packs)
        {
            PanelControlTester packListControlTester = new PanelControlTester("packListPanel", "PackInstallerForm");
            bool packFound;

            int visiblePacks = 0;
            foreach (Control pack in packListControlTester.InnerControls)
            {
                if (pack.Visible == true)
                {
                    visiblePacks++;
                }
            }
            if (packs.Length != visiblePacks)
            {
                errorMessages.Add("Expected " + packs.Length + " visible packs but found " + visiblePacks);
            }

            foreach (string packname in packs)
            {
                packFound = false;
                foreach (Control pack in packListControlTester.InnerControls)
                {
                    if ((packname == pack.Name) && (pack.Visible == true))
                    {
                        packFound = true;
                        break;
                    }
                }
                if (packFound == false)
                {
                    errorMessages.Add("The " + packname + " pack was not found or was not visible.");
                }
            }
        }

        private void VerifyAllPacks(string[] packs)
        {
            PanelControlTester packListControlTester = new PanelControlTester("packListPanel", "PackInstallerForm");
            bool packFound;

            if (packs.Length != packListControlTester.InnerControls.Count)
            {
                errorMessages.Add("Expected " + packs.Length + " packs but found " + packListControlTester.InnerControls.Count);
            }

            foreach (string packname in packs)
            {
                packFound = false;
                foreach (Control pack in packListControlTester.InnerControls)
                {
                    if (packname == pack.Name)
                    {
                        packFound = true;
                        break;
                    }
                }
                if (packFound == false)
                {
                    errorMessages.Add("The " + packname + " pack was not found.");
                }
            }
        }

        private void FindManagedStackExplorer(string packname, int position)
        {
            PackListControlTester packListTester = new PackListControlTester(packname, "PackInstallerForm");
            bool toolFound = false;
            int foundPosition = 0;

            foreach (ToolItem tool in packListTester.Properties.CurrentPackData.Tools)
            {
                foundPosition++;
                if (tool.ToolName.Contains("Managed Stack Explorer"))
                {
                    toolFound = true;
                    break;
                }
            }
            if (toolFound != true)
            {
                errorMessages.Add("ToolSortHandler: Managed Stack Explorer was not found in the " + packname + " pack.");
            }
            else
            {
                if (foundPosition != position)
                {
                    errorMessages.Add("ToolSortHandler: Managed Stack Explorer was found in position: " + foundPosition + " rather than the expected position " + position);
                }
            }
        }

        private void DeclineLicenseFormHandler()
        {
            ButtonTester buttonTester = new ButtonTester("declineButton", "MultipleLicenseAgreementForm");
            buttonTester.Click();
        }

        #endregion

        #region Search Tests

        /// <summary>
        /// This test verifies Pack Installer behavior when the user 
        /// searches for tools using the search text box and when the user clicks
        /// All to redisplay all tools after searching
        /// </summary>
        [Test]
        public void ToolSearchTest()
        {
            errorMessages = new ErrorMessages();
            tripCount = 0;

            // Install the Managed Stack Explorer so we know that searching works with installed tools
            InstallManagedStackExplorer();

            // Do the search test logic
            packInstallForm = new PackInstallerForm("");
            packInstallForm.OnPacksLoaded += new EventHandler<EventArgs>(ToolSearchHandler);
            ExpectModal("PackInstallerForm", "GenericFormHandler");
            packInstallForm.ShowDialog();

            // Removel the Managed Stack Explorer 
            RemoveManagedStackExplorer();

            errorMessages.printErrors("ToolSearchTest");
            Assert.AreEqual(0, errorMessages.Count, "ToolSearchTest failed. Check Console output for error messages.");
        }

        /// <summary>
        /// Logic for the ToolSearchTest
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToolSearchHandler(object sender, EventArgs e)
        {
            ButtonTester buttonTester = new ButtonTester("refreshListButton", "PackInstallerForm");
            TextBoxTester textBoxtester = new TextBoxTester("typeAlongSearchTextBox", "PackInstallerForm");
            
            if (tripCount == 1)
            {
                tripCount++;

                // Verify name searches 
                // Should find only the Managed Stack Explorer
                SearchForName("Managed Stack Explorer");

                // Should find all tools with XML in the name
                // LOW RISK - May break if a tool has XML in the description but not in the name
                SearchForName("XML");

                // Should find all tools with microsoft in the name
                // LOW RISK - May break if a tool has Microsoft in the description but not in the name
                //SearchForName("microsoft");

                // Should find the Managed Stack Explorer and any other tool with explorer in the name
                // LOW RISK - May break if a tool has explorer in the description but not in the name
                SearchForName("explorer");

                // Verify that a search also searches description data
                // To do this, we search for "util" and verify that we get back at least ILMerge and TFS Admin tools
                // Their respective descriptions contain "utility" and "utilized" but 'util' is not in the tools name.
                textBoxtester.Enter("util");
                string[] expectedTools = { "ILMerge", "TFS Administration Tool" };
                int foundTools = 0;
                PanelControlTester packListControlTester = new PanelControlTester("packListPanel", "PackInstallerForm");
                foreach (Control pack in packListControlTester.InnerControls)
                {
                    PackListControlTester packListTester = new PackListControlTester(pack.Name, "PackInstallerForm");
                    PanelControlTester toolsPanelTester = new PanelControlTester(pack.Name + ".toolsPanel", "PackInstallerForm");

                    // Verify that at least the two expected tools are displayed 
                    // Other tools with util in the description or title 
                    // may show up in the future without breaking the test.
                    foreach (Control tool in toolsPanelTester.InnerControls)
                    {
                        if ((tool.Visible) &&
                            ((tool.Name == expectedTools[0]) || (tool.Name == expectedTools[1])))
                        {
                            foundTools++;
                        }
                    }
                }
                if (foundTools != 2)
                    errorMessages.Add("Searching for 'util' did not find " + expectedTools[0] + " and " + expectedTools[1]);

                // Redisplay all tools by clicking Show All
                LabelTester showAllTester = new LabelTester("showAllTagItemControl.tagNameLabel", "PackInstallerForm");
                showAllTester.Click();

                // If clicking Show All did not redisplay all the tools,
                // MSE's checkbox will not be visible

                CheckBoxTester managedStackExplorertoolCheckBoxTester = new CheckBoxTester("Tools and Utilities.toolsPanel.Managed Stack Explorer.layoutPanel.installToolCheckBox", "PackInstallerForm");
                if (managedStackExplorertoolCheckBoxTester.Properties.Visible == false)
                {
                    errorMessages.Add("Clicking the All control did not redisplay all tools.");
                }
                if (textBoxtester.Text != "")
                {
                    errorMessages.Add("Clicking the All control did not clear search text. Text == '" + textBoxtester.Text + "'");
                }

                // Click the Refresh List button so the test will exit
                buttonTester.Click();
            }
            else
            {
                // After it refreshes, click the Exit button.
                buttonTester = new ButtonTester("exitButton", "PackInstallerForm");
                buttonTester.Click();
            }
        }

        /// <summary>
        /// Method enters the parameter string into the search text box
        /// and verifies that all tools displayed have that string in the tool name
        /// </summary>
        /// <param name="toolName"></param>
        private void SearchForName(string toolName)
        {
            string expectedString = toolName.ToLower(System.Globalization.CultureInfo.CurrentCulture);
            TextBoxTester textBoxtester = new TextBoxTester("typeAlongSearchTextBox", "PackInstallerForm");
            textBoxtester.Enter(expectedString);

            PanelControlTester packListControlTester = new PanelControlTester("packListPanel", "PackInstallerForm");
            foreach (Control pack in packListControlTester.InnerControls)
            {
                PackListControlTester packListTester = new PackListControlTester(pack.Name, "PackInstallerForm");
                PanelControlTester toolsPanelTester = new PanelControlTester(pack.Name + ".toolsPanel", "PackInstallerForm");

                // Verify that each tool that is displayed in this pack contains the expected string
                foreach (Control tool in toolsPanelTester.InnerControls)
                {
                    if ((tool.Visible) && (!tool.Name.ToLower(System.Globalization.CultureInfo.CurrentCulture).Contains(expectedString)))
                    {
                        errorMessages.Add("Tool '" + tool.Name + "' in Pack '" + pack.Name + "' does not contain " + expectedString);
                    }
                }
            }
        }

        #endregion

        #region Filter tests

        /// <summary>
        /// Validates the expected display C# tools for several filtering tests
        /// </summary>
        private void CSharpFilterValidation()
        {
            string [] expectedPacks = { "Code Samples and Snippets", "Starter Kits" };
            string[] expectedTools = {"Visual C# 2005 Code Snippets", 
                                      "101 Samples for Visual Studio 2005 (Visual C#)", "Shareware Starter Kit (Visual C#)"};
            int filteredToolCount = 0;
            // Get total number of C# tools.
            PanelControlTester packListControlTester = new PanelControlTester("packListPanel", "PackInstallerForm");
            foreach (Control pack in packListControlTester.InnerControls)
            {
                PackListControlTester packListTester = new PackListControlTester(pack.Name, "PackInstallerForm");
                PanelControlTester toolsPanelTester = new PanelControlTester(pack.Name + ".toolsPanel", "PackInstallerForm");
                if (packListTester.Properties.Visible)
                {
                    bool packBelongsInDisplay = false;
                    foreach (string expectedPackName in expectedPacks)
                    {
                        if (pack.Name == expectedPackName)
                        {
                            packBelongsInDisplay = true;
                            break;
                        }
                    }
                    if (packBelongsInDisplay != true)
                    {
                        errorMessages.Add("Unexpected pack displayed - '" + pack.Name + "'");
                    }
                    foreach (Control tool in toolsPanelTester.InnerControls)
                    {
                        bool toolBelongsInDisplay = false;
                        foreach (string toolName in expectedTools)
                        {
                            if (toolName == tool.Name)
                            {
                                toolBelongsInDisplay = true;
                                break;
                            }
                        }

                        if (tool.Visible == true)
                        {
                            filteredToolCount++;
                            if (toolBelongsInDisplay != true)
                            {
                                errorMessages.Add("Unexpected tool '" + tool.Name + "' was displayed.");
                            }
                        }
                        else 
                        {
                            if (toolBelongsInDisplay == true)
                            {
                                errorMessages.Add("Expected tool '" + tool.Name + "' is not displayed.");
                            }
                        }
                    }
                }
            }

            if (filteredToolCount != expectedTools.Length)
            {
                errorMessages.Add("Expected " + expectedTools.Length + " C# tools but found " + filteredToolCount);
            }
        }

        /// <summary>
        /// This test verifies Pack Installer behavior when the user
        /// 1. Filters in Install mode
        /// 2. Switches to Removal mode
        /// 3. Returns to Install mode
        /// </summary>
        [Test]
        public void FilterAndSwitchModesTest()
        {
            errorMessages = new ErrorMessages();

            tripCount = 0;

            // Install the Managed Stack Explorer 
            InstallManagedStackExplorer();

            packInstallForm = new PackInstallerForm(TestStrings.GeneralTestPackFeedXml);
            packInstallForm.OnPacksLoaded += new EventHandler<EventArgs>(FilterAndSwitchModesHandler);

            ExpectModal("PackInstallerForm", "GenericFormHandler");
            packInstallForm.ShowDialog();

            // Removel the Managed Stack Explorer
            tripCount++;
            RemoveManagedStackExplorer();

            errorMessages.printErrors("FilterAndSwitchModesTest");
            Assert.AreEqual(0, errorMessages.Count, "FilterAndSwitchModesTest failed. Check Console output for error messages.");
        }

        /// <summary>
        /// Logic for FilterAndSwitchModesTest
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FilterAndSwitchModesHandler(object sender, EventArgs e)
        {
            ButtonTester refreshListButtonTester = new ButtonTester("refreshListButton", "PackInstallerForm");

            string tagControl = "Visual C#TagControl.tagNameLabel";
            ControlTester tagTester = new ControlTester(tagControl) ;

            RadioButtonTester installRadioTester = new RadioButtonTester("headerPanel.installationRadio", "PackInstallerForm");
            // Make sure we are in install mode
            installRadioTester.Click();

            // Filter by C# tools
            tagTester.Click();
            CSharpFilterValidation();

            // Click the maintenanceRadio button
            RadioButtonTester maintenanceRadioTester = new RadioButtonTester("headerPanel.maintenanceRadio", "PackInstallerForm");
            maintenanceRadioTester.Click();

            // Verify that Pack Installer displays an unfiltered list of installed tools
            // If clicking the maintenanceRadio button did not display 
            // an unfiltered list of installed tools, MSE's checkbox will not be visible
            CheckBoxTester managedStackExplorertoolCheckBoxTester = new CheckBoxTester("Tools and Utilities.toolsPanel.Managed Stack Explorer.layoutPanel.installToolCheckBox", "PackInstallerForm");
            if (managedStackExplorertoolCheckBoxTester.Properties.Visible == false)
            {
                errorMessages.Add("Clicking the maintenanceRadio button did not display installed tools.");
            }

            // Verify that tagAndFilterControl is disabled
            TagAndFilterControlTester ct = new TagAndFilterControlTester("tagAndFilterControl", "PackInstallerForm");
            if (ct.Properties.Enabled == true)
            {
                errorMessages.Add("tagAndFilterControl is enabled in Removal mode.");
            }

            // Switch back to install mode
            installRadioTester.Click();

            // Verify that tagAndFilterControl is now enabled
            if (ct.Properties.Enabled == false)
            {
                errorMessages.Add("tagAndFilterControl is disabled in Install mode.");
            }

            // Verify that all tools are displayed 
            PanelControlTester packListControlTester = new PanelControlTester("packListPanel", "PackInstallerForm");
            foreach (Control pack in packListControlTester.InnerControls)
            {
                PackListControlTester packListTester = new PackListControlTester(pack.Name, "PackInstallerForm");
                PanelControlTester toolsPanelTester = new PanelControlTester(pack.Name + ".toolsPanel", "PackInstallerForm");
                foreach (Control tool in toolsPanelTester.InnerControls)
                {
                    if (tool.Visible == false)
                    {
                        errorMessages.Add(tool.Name + " is not visible after clicking Install radio button");
                    }
                }
            }

            ButtonTester exitButton = new ButtonTester("exitButton", "PackInstallerForm");
            exitButton.Click();
        }

        /// <summary>
        /// This test Pack Installer behavior when the users
        /// filters on the C# tag in Install mode and clicks the refresh button.
        /// The expected behavior is that the Pack Insatller still filters the display.
        /// </summary>
        [Test]
        public void FilterAndRefreshTest()
        {
            errorMessages = new ErrorMessages();
            tripCount = 0;
            packInstallForm = new PackInstallerForm(TestStrings.GeneralTestPackFeedXml);
            packInstallForm.OnPacksLoaded += new EventHandler<EventArgs>(FilterAndRefreshHandler);

            ExpectModal("PackInstallerForm", "GenericFormHandler");
            packInstallForm.ShowDialog();

            errorMessages.printErrors("FilterAndRefreshTest");
            Assert.AreEqual(0, errorMessages.Count, "FilterAndRefreshTest failed. Check Console output for error messages.");
        }

        /// <summary>
        /// Logic for the FilterAndRefreshTest
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void FilterAndRefreshHandler(object sender, EventArgs e)
        {
            ButtonTester refreshListButtonTester = new ButtonTester("refreshListButton", "PackInstallerForm");

            string tagControl = "Visual C#TagControl.tagNameLabel";
            ControlTester tagTester = new ControlTester(tagControl);

            if (tripCount == 0)
            {
                tripCount++;
                // Filter by C# tools
                tagTester.Click();
                // Validate the filtered display
                CSharpFilterValidation();
                // Click the refresh button which 
                // will cause us to come back and execute the else clause
                refreshListButtonTester.Click();
            }
            else 
            {
                // Validate the filtered display and close the Pack Installer form
                CSharpFilterValidation();
                ButtonTester exitButton = new ButtonTester("exitButton", "PackInstallerForm");
                exitButton.Click();
            }
        }

        /// <summary>
        /// This test verifies Pack Installer behavior when the user:
        /// 1. Filters on C# in Install mode
        /// 2. Starts to install some tools but declines the license agreements
        /// 3. The expected behavior is that the Pack Insatller still filters the display 
        /// </summary>
        [Test]
        public void FilterAndDeclineLicenseTest()
        {
            errorMessages = new ErrorMessages();
            tripCount = 0;
            packInstallForm = new PackInstallerForm(TestStrings.GeneralTestPackFeedXml);
            packInstallForm.OnPacksLoaded += new EventHandler<EventArgs>(FilterAndDeclineLicenseHandler);

            ExpectModal("PackInstallerForm", "GenericFormHandler");
            packInstallForm.ShowDialog();

            errorMessages.printErrors("FilterAndDeclineLicenseTest");
            Assert.AreEqual(0, errorMessages.Count, "FilterAndDeclineLicenseTest failed. Check Console output for error messages.");
        }

        /// <summary>
        /// Logic for the FilterAndDeclineLicenseTest
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FilterAndDeclineLicenseHandler(object sender, EventArgs e)
        {
            string tagControl = "Visual C#TagControl.tagNameLabel";
            ControlTester tagTester = new ControlTester(tagControl);

            RadioButtonTester installRadioTester = new RadioButtonTester("headerPanel.installationRadio", "PackInstallerForm");
            // Make sure we are in install mode
            installRadioTester.Click();

            // Filter by C# tools
            tagTester.Click();
            CSharpFilterValidation();
            PanelControlTester packListControlTester = new PanelControlTester("packListPanel", "PackInstallerForm");
            foreach (Control pack in packListControlTester.InnerControls)
            {
                PackListControlTester packListTester = new PackListControlTester(pack.Name, "PackInstallerForm");
                PanelControlTester toolsPanelTester = new PanelControlTester(pack.Name + ".toolsPanel", "PackInstallerForm");
                CheckBoxTester installPackCheckBoxTester = new CheckBoxTester(pack.Name + ".headerPanel.installPackCheckBox");

                // Check each Pack for installation
                if (installPackCheckBoxTester.Properties.Visible)
                    installPackCheckBoxTester.Click();
            }

            ButtonTester installSoftwareButtonTester = new ButtonTester("installSoftwareButton", "PackInstallerForm");
            // Verify that the Install button is enabled
            if (installSoftwareButtonTester.Properties.Enabled != true)
            {
                errorMessages.Add("Install software button is disabled after one tool was selected.");
            }

            // Need an ExpectModal to handle the license download and agreement forms.
            // If we decline the license we do NOT expect a progress form to be displayed
            // so we intentionally do not put an ExpectModal for it. Then, if one is displayed 
            // the test will fail due to the unexpected dialog form showing up.
            ExpectModal("LicenseAgreementDownloadForm", "GenericFormHandler");
            ExpectModal("MultipleLicenseAgreementForm", "DeclineLicenseFormHandler");
            installSoftwareButtonTester.Click();
            CSharpFilterValidation();
            ButtonTester exitButton = new ButtonTester("exitButton", "PackInstallerForm");
            exitButton.Click();
        }

        /// <summary>
        /// This test verifies Pack Installer behavior when the user filters on C# in 
        /// Install mode and installs some tools 
        /// The expected behavior is that the Pack Insatller still filters the display 
        /// </summary>
        [Test]
        public void FilterAndInstallTest()
        {
            errorMessages = new ErrorMessages();
            tripCount = 0;
            packInstallForm = new PackInstallerForm(TestStrings.GeneralTestPackFeedXml);
            packInstallForm.OnPacksLoaded += new EventHandler<EventArgs>(FilterAndInstallHandler);
            packInstallForm.OnToolsInstalled += new EventHandler<EventArgs>(InstallProgressFormHandler);
            installedToolCount = 3;

            ExpectModal("PackInstallerForm", "GenericFormHandler");
            packInstallForm.ShowDialog();

            // Remove the installed packs 
            RemoveInstalledPacks();

            errorMessages.printErrors("FilterAndInstallTest");
            Assert.AreEqual(0, errorMessages.Count, "FilterAndInstallTest failed. Check Console output for error messages.");
        }

        /// <summary>
        /// Logic for the FilterAndInstallTest
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FilterAndInstallHandler(object sender, EventArgs e)
        {
            string tagControl = "Tools and UtilitiesTagControl.tagNameLabel";
            ControlTester tagTester = new ControlTester(tagControl);
            string expectedPack = "Tools and Utilities";
            ButtonTester installSoftwareButtonTester = new ButtonTester("installSoftwareButton", "PackInstallerForm");
            PanelControlTester packListControlTester = new PanelControlTester("packListPanel", "PackInstallerForm");

            if (tripCount == 0)
            {
                tripCount++;
                RadioButtonTester installRadioTester = new RadioButtonTester("headerPanel.installationRadio", "PackInstallerForm");
                // Make sure we are in install mode
                installRadioTester.Click();

                // Filter by Debugging tools
                tagTester.Click();
                foreach (Control pack in packListControlTester.InnerControls)
                {
                    PackListControlTester packListTester = new PackListControlTester(pack.Name, "PackInstallerForm");
                    PanelControlTester toolsPanelTester = new PanelControlTester(pack.Name + ".toolsPanel", "PackInstallerForm");
                    CheckBoxTester installPackCheckBoxTester = new CheckBoxTester(pack.Name + ".headerPanel.installPackCheckBox");

                    // Check each Pack for installation
                    if (installPackCheckBoxTester.Properties.Visible)
                    {
                        installPackCheckBoxTester.Click();
                        if (pack.Name != expectedPack)
                            errorMessages.Add("Unexpected pack '" + pack.Name + "' is visible.");
                    }
                }

                // Verify that the Install button is enabled
                if (installSoftwareButtonTester.Properties.Enabled != true)
                {
                    errorMessages.Add("Install software button is disabled after tools were selected.");
                }

                // Now Install the packs
                // Set up the handler's for the forms
                ExpectModal("ProgressResultsForm", "GenericFormHandler");
                ExpectModal("LicenseAgreementDownloadForm", "GenericFormHandler");
                ExpectModal("MultipleLicenseAgreementForm", "LicenseFormHandler");
                installSoftwareButtonTester.Click();
            }
            else if (tripCount == 1)
            {
                tripCount++;
                // Verify that after installation, the filter is still honored.
                foreach (Control pack in packListControlTester.InnerControls)
                {
                    PackListControlTester packListTester = new PackListControlTester(pack.Name, "PackInstallerForm");
                    PanelControlTester toolsPanelTester = new PanelControlTester(pack.Name + ".toolsPanel", "PackInstallerForm");
                    CheckBoxTester installPackCheckBoxTester = new CheckBoxTester(pack.Name + ".headerPanel.installPackCheckBox");

                    // Check each Pack for installation
                    if (installPackCheckBoxTester.Properties.Visible)
                    {
                        installPackCheckBoxTester.Click();
                        if (pack.Name != expectedPack)
                            errorMessages.Add("Unexpected pack '" + pack.Name + "' is visible.");
                    }
                }

                ButtonTester exitButton = new ButtonTester("exitButton", "PackInstallerForm");
                exitButton.Click();
            }
        }

        /// <summary>
        /// This test verifies Pack Installer behavior when the user:
        /// 1. Searches for tools using the search text box
        /// 2. Applies filters within the search results
        /// 3. Clicks Show All to restore all tools to the display
        /// </summary>
        [Test]
        public void ToolSearchAndFilterTest()
        {
            errorMessages = new ErrorMessages();

            packInstallForm = new PackInstallerForm(TestStrings.GeneralTestPackFeedXml);
            packInstallForm.OnPacksLoaded += new EventHandler<EventArgs>(ToolSearchAndFilterHandler);
            packInstallForm.OnToolsInstalled += new EventHandler<EventArgs>(InstallProgressFormHandler);
            installedToolCount = 1;
            ExpectModal("PackInstallerForm", "GenericFormHandler");
            packInstallForm.ShowDialog();

            errorMessages.printErrors("ToolSearchAndFilterTest");
            Assert.AreEqual(0, errorMessages.Count, "ToolSearchAndFilterTest failed. Check Console output for error messages.");
        }

        static int toolCount = 0;

        /// <summary>
        /// Logic for the ToolSearchAndFilterTest
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ToolSearchAndFilterHandler(object sender, EventArgs e)
        {
            ButtonTester buttonTester = new ButtonTester("refreshListButton", "PackInstallerForm");
            TextBoxTester textBoxtester = new TextBoxTester("typeAlongSearchTextBox", "PackInstallerForm");
            PanelControlTester packListControlTester = new PanelControlTester("packListPanel", "PackInstallerForm");
            ControlTester tagTester;
            bool foundCurrentTool = false;
            int foundTools = 0;
            string tagControl = "TagControl.tagNameLabel";
            string[] expectedTools = { 
                    "VSCommand Shell",  "Microsoft Printer Compatibility Library",
                    "Visual C# 2005 Code Snippets", "101 Samples for Visual Studio 2005 (Visual C#)", 
                    "101 Samples for Visual Studio 2005 (Visual Basic)", 
                "Shareware Starter Kit (Visual C#)", 
                "Shareware Starter Kit (Visual Basic)", };
            string[] sampleTools = {"101 Samples for Visual Studio 2005 (Visual C#)", "Visual C# 2005 Code Snippets",
                                      "101 Samples for Visual Studio 2005 (Visual Basic)"};

            // Get total number of tools in the unfiltered display.
            foreach (Control pack in packListControlTester.InnerControls)
            {
                PackListControlTester packListTester = new PackListControlTester(pack.Name, "PackInstallerForm");
                PanelControlTester toolsPanelTester = new PanelControlTester(pack.Name + ".toolsPanel", "PackInstallerForm");
                foreach (Control tool in toolsPanelTester.InnerControls)
                {
                    toolCount++;
                }
            }

            // Search to find all tools with visual in the name or description
            textBoxtester.Enter("visual");

            // Verify that the expected tools are displayed 
            foreach (string toolName in expectedTools)
            {
                foundCurrentTool = false;
                foreach (Control pack in packListControlTester.InnerControls)
                {
                    PackListControlTester packListTester = new PackListControlTester(pack.Name, "PackInstallerForm");
                    PanelControlTester toolsPanelTester = new PanelControlTester(pack.Name + ".toolsPanel", "PackInstallerForm");

                    // We cannot just use the tool name to find the controls because they contain blanks.
                    // The GUI test package throws a "NoSuchControl" exception when the control name 
                    // contains certain punctuation characters.
                    foreach (Control tool in toolsPanelTester.InnerControls)
                    {
                        if ((tool.Name == toolName) && (tool.Visible))
                        {
                            foundCurrentTool = true;
                        }
                    }
                }
                if (foundCurrentTool == false)
                    errorMessages.Add("Searching for 'visual' did not find " + toolName);
            }

            // Verify that the visible tool count matches the number of tools in the 
            // expected tools list
            string foundToolsNames = String.Empty;
            foreach (Control pack in packListControlTester.InnerControls)
            {
                PackListControlTester packListTester = new PackListControlTester(pack.Name, "PackInstallerForm");
                PanelControlTester toolsPanelTester = new PanelControlTester(pack.Name + ".toolsPanel", "PackInstallerForm");
                foreach (Control tool in toolsPanelTester.InnerControls)
                {
                    if (tool.Visible)
                    {
                        foundTools++;
                        foundToolsNames += "        " + tool.Name + Environment.NewLine;
                    }
                }
            }
            if (foundTools != expectedTools.Length)
            {
                errorMessages.Add("After searching for 'visual: expected " + expectedTools.Length + " but found " + foundTools + Environment.NewLine + "The found tools were:" + Environment.NewLine + foundToolsNames);
            }

            // Filter by Code Samples and Snippets within the search results.
            tagTester = new ControlTester("Code Samples and Snippets" + tagControl);
            tagTester.Click();

            // Should now find only the tools in sampleTools.
            // First, verify that the expected sample tools are displayed
            foreach (string toolName in sampleTools)
            {
                foundCurrentTool = false;
                foreach (Control pack in packListControlTester.InnerControls)
                {
                    PackListControlTester packListTester = new PackListControlTester(pack.Name, "PackInstallerForm");
                    PanelControlTester toolsPanelTester = new PanelControlTester(pack.Name + ".toolsPanel", "PackInstallerForm");

                    // We cannot just use the tool name to find the controls because they contain blanks.
                    // The GUI test package throws a "NoSuchControl" exception when the control name 
                    // contains certain punctuation characters.
                    foreach (Control tool in toolsPanelTester.InnerControls)
                    {
                        if ((tool.Visible) && (tool.Name == toolName))
                        {
                            foundCurrentTool = true;
                        }

                    }
                }
                if (foundCurrentTool == false)
                    errorMessages.Add("Filtering for 'Code Samples and Snippets' did not find " + toolName);
            }

            // Finally, just in case some tools that weren't part of the search results
            // sneak into the display, check the number of visible tools against the 
            // number of entries in the Samples list.
            foundTools = 0;
            foundToolsNames = String.Empty;
            foreach (Control pack in packListControlTester.InnerControls)
            {
                PackListControlTester packListTester = new PackListControlTester(pack.Name, "PackInstallerForm");
                PanelControlTester toolsPanelTester = new PanelControlTester(pack.Name + ".toolsPanel", "PackInstallerForm");

                // We cannot just use the tool name to find the controls because they contain blanks.
                // The GUI test package throws a "NoSuchControl" exception when the control name 
                // contains a blank
                foreach (Control tool in toolsPanelTester.InnerControls)
                {
                    if (tool.Visible)
                    {
                        foundTools++;
                        foundToolsNames += "        " + tool.Name + Environment.NewLine;
                    }
                }
            }
            if (foundTools != sampleTools.Length)
                errorMessages.Add("Filtering for 'Code Samples and Snippets' expected " + sampleTools.Length + " entries but found " + foundTools + Environment.NewLine + "The found tools were:" + Environment.NewLine + foundToolsNames);

            // Redisplay all tools by clicking Show All
            LabelTester showAllTester = new LabelTester("showAllTagItemControl.tagNameLabel", "PackInstallerForm");
            showAllTester.Click();

            // If clicking Show All did not redisplay all the tools,
            // MSE's checkbox will not be visible

            CheckBoxTester managedStackExplorertoolCheckBoxTester = new CheckBoxTester("Tools and Utilities.toolsPanel.Managed Stack Explorer.layoutPanel.installToolCheckBox", "PackInstallerForm");
            if (managedStackExplorertoolCheckBoxTester.Properties.Visible == false)
            {
                errorMessages.Add("Clicking the All label did not redisplay Managed Stack Explorer.");
            }

            // Verify that the number of visible tools matches the original count
            foundTools = 0;
            foreach (Control pack in packListControlTester.InnerControls)
            {
                PackListControlTester packListTester = new PackListControlTester(pack.Name, "PackInstallerForm");
                PanelControlTester toolsPanelTester = new PanelControlTester(pack.Name + ".toolsPanel", "PackInstallerForm");

                // Verify that all tools are displayed 
                foreach (Control tool in toolsPanelTester.InnerControls)
                {
                    if (tool.Visible)
                    {
                        foundTools++;
                    }
                    else
                    {
                        errorMessages.Add(tool.Name + " is not visible after clicking All");
                    }
                }
            }
            if (foundTools != toolCount)
                errorMessages.Add("All restored " + foundTools + " of " + toolCount + " tools to display. ");

            // Click the Exit button.
            buttonTester = new ButtonTester("exitButton", "PackInstallerForm");
            buttonTester.Click();
        }

        #endregion

     }
}
